#include "abstract-database-client.h"
#include "abstract-queries.h"
#include "model-result.h"
#include "standard-database-delegate.h"

StandardDatabaseDelegate::StandardDatabaseDelegate(QObject *parent) :
    ComboBoxDelegate(parent), m_nullIncluded(true)
{
}

void StandardDatabaseDelegate::setDatabaseClient (QSharedPointer<AbstractDatabaseClient> databaseClient)
{
    m_databaseClient = databaseClient;
}

void StandardDatabaseDelegate::setLoadingParameters (const QVariantList& parameters)
{
    m_loadingParameters = parameters;
}

void StandardDatabaseDelegate::setLoadingParameter (const QVariant& parameter)
{
    m_loadingParameters = QVariantList() << parameter;
}

void StandardDatabaseDelegate::setNullIncluded (bool included)
{
    m_nullIncluded = included;
}

void StandardDatabaseDelegate::initialize()
{
    ModelResult* result = m_databaseClient->selectModel(m_queries->selectQuery(0, 0), m_loadingParameters);
    connect (result, SIGNAL(resultReady(ModelResult*)), this, SLOT(finishInitialize(ModelResult*)));
}

void StandardDatabaseDelegate::finishInitialize (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit initialized();
        return;
    }

    QAbstractTableModel* model = result->model();
    setupInternalModel(model);

    if (m_nullIncluded)
        m_comboBoxData.append(qMakePair(QString("brak"), QVariant(QVariant::Int)));

    for (int i = 0; i < model->rowCount(); i++)
        m_comboBoxData.append(qMakePair(model->index(i, 1).data().toString(), QVariant(model->index(i, 0).data().toInt())));

    emit initialized();
}

void StandardDatabaseDelegate::setupInternalModel(QAbstractTableModel *model)
{
    Q_UNUSED(model);
}
